<template>
  <div>
    <el-autocomplete v-model="input"
      :placeholder="placeholder"
      :maxlength="clearValidate ?200:11"
      :fetch-suggestions="querySearch"
      popper-class="phone-autocomplete"
      autocomplete='off'
      @focus="$emit('focus')"
      @select="handleSelect">
      <template #default="{ item }">
        <div class="name">{{ item.value }}</div>
        <span class="addr">{{ item.address }}</span>
      </template>
    </el-autocomplete>
  </div>
</template>

<script lang="ts">
import { getTypeOf } from '@/utils'
export default {
  name: 'PhoneInput',
  props: {
    value: null,
    placeholder: {
      type: String,
      default: '请输入您的手机号'
    },
    clearValidate: {
      type: Boolean,
      default: false
    }
  },
  emits: ['selectPhone', 'input', 'focus'],
  computed: {
    input: {
      get () {
        return this.value
      },
      set (val: any) {
        if (!this.clearValidate) {
          val = val.replace(/[^\d]/g, '')
        }
        this.$emit('input', val)
      }
    }
  },
  created () {
    let list: any = localStorage.getItem('phoneAccount')

    if (!list) {
      list = []
    }

    try {
      list = JSON.parse(list)
      if (getTypeOf(list) !== 'array') {
        list = []
      }
    } catch (e) {
      list = []
    }
    this.phoneList = list
    // this.phoneAccount = []
    // this.getList = debounce(() => {
    this.phoneAccount = this.phoneList.map((item: any) => {
      return {
        ...item,
        value: item.a || ''
      }
    })
    // }, 1000, true)
  },
  methods: {
    /**
     * 手机输入框-返回建议列表的数据
     * @param {String} queryString
     * @param {Function} cb
     */
    querySearch (queryString: any, cb: any) {
      cb(queryString.length < 11 ? this.phoneAccount : [])
    },
    /**
     * 手机输入框-建议列表选中事件
     * @param {String} queryString
     * @param {Function} cb
     */
    handleSelect (data: any) {
      this.$emit('selectPhone', data)
    }
  }
}
</script>
<style lang="scss" scoped>
.el-autocomplete {
  width: 100%;
}
</style>
<style lang="scss">
.phone-autocomplete {
  margin-top: -14px !important;
  width: 130px !important;
  margin-left: 140px !important;
  .el-scrollbar__wrap {
    padding: 0;
  }
}
</style>
